package com.zw.aspect;
import com.zw.pojo.RequestInfoDto;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
@Aspect
public class CustomAspect {

    @Pointcut("@annotation(com.zw.annotation.ParametersCheckout)")
    public void pointCut(){
    }

    /**
     * 通过环绕增强处理请求参数基本校验
     * @param joinPoint
     * @return
     */
    /*@Around(value = "pointCut()")
    public Object around(ProceedingJoinPoint joinPoint){
        //用于校验请求参数格式以及是否必填
        Object[] args = joinPoint.getArgs();
        if (Objects.nonNull(args) && args.length>0){
            RequestInfoDto requestInfoDto =(RequestInfoDto) args[0];
           if (Objects.isNull(requestInfoDto.getName())|| Objects.isNull(requestInfoDto.getSex())
           ||Objects.isNull(requestInfoDto.getAge())){
               return "请求参数异常！";
           }
        }
        Object proceed=null;
        try {
             proceed = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
         return proceed;
    }*/

    /**
     * 通过前置增强处理请求参数校验
     * @return
     */
    @Before(value = "pointCut()")
    public void before(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        System.out.println("request参数为:"+args[0]);
        if (Objects.nonNull(args) && args.length>0){
            RequestInfoDto requestInfoDto =(RequestInfoDto) args[0];
            if (Objects.isNull(requestInfoDto.getName())|| Objects.isNull(requestInfoDto.getSex())
                    ||Objects.isNull(requestInfoDto.getAge())){
                throw new RuntimeException("请求参数异常！");
            }
        }
    }
}
